home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 1998 November / IRIX 6.5.2 Base Documentation November 1998.img / usr / share / catman / u_man / cat1 / perlobj.z / perlobj
Text File  |  1998-10-30  |  23KB  |  661 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))                                                          PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perlobj - Perl objects
  10.  
  11. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.      First of all, you need to understand what references are in Perl.  See
  13.      the _p_e_r_l_r_e_f manpage for that.  Second, if you still find the following
  14.      reference work too complicated, a tutorial on object-oriented programming
  15.      in Perl can be found in the _p_e_r_l_t_o_o_t manpage.
  16.  
  17.      If you're still with us, then here are three very simple definitions that
  18.      you should find reassuring.
  19.  
  20.      1.  An object is simply a reference that happens to know which class it
  21.          belongs to.
  22.  
  23.      2.  A class is simply a package that happens to provide methods to deal
  24.          with object references.
  25.  
  26.      3.  A method is simply a subroutine that expects an object reference (or
  27.          a package name, for class methods) as the first argument.
  28.  
  29.      We'll cover these points now in more depth.
  30.  
  31.      AAAAnnnn OOOObbbbjjjjeeeecccctttt iiiissss SSSSiiiimmmmppppllllyyyy aaaa RRRReeeeffffeeeerrrreeeennnncccceeee
  32.  
  33.      Unlike say C++, Perl doesn't provide any special syntax for constructors.
  34.      A constructor is merely a subroutine that returns a reference to
  35.      something "blessed" into a class, generally the class that the subroutine
  36.      is defined in.  Here is a typical constructor:
  37.  
  38.          package Critter;
  39.          sub new { bless {} }
  40.  
  41.      The {} constructs a reference to an anonymous hash containing no
  42.      key/value pairs.  The _b_l_e_s_s() takes that reference and tells the object
  43.      it references that it's now a Critter, and returns the reference.  This
  44.      is for convenience, because the referenced object itself knows that it
  45.      has been blessed, and the reference to it could have been returned
  46.      directly, like this:
  47.  
  48.          sub new {
  49.              my $self = {};
  50.              bless $self;
  51.              return $self;
  52.          }
  53.  
  54.      In fact, you often see such a thing in more complicated constructors that
  55.      wish to call methods in the class as part of the construction:
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))                                                          PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  71.  
  72.  
  73.  
  74.          sub new {
  75.              my $self = {}
  76.              bless $self;
  77.              $self->initialize();
  78.              return $self;
  79.          }
  80.  
  81.      If you care about inheritance (and you should; see the section on
  82.      _M_o_d_u_l_e_s: _C_r_e_a_t_i_o_n, _U_s_e, _a_n_d _A_b_u_s_e in the _p_e_r_l_m_o_d manpage), then you want
  83.      to use the two-arg form of bless so that your constructors may be
  84.      inherited:
  85.  
  86.          sub new {
  87.              my $class = shift;
  88.              my $self = {};
  89.              bless $self, $class
  90.              $self->initialize();
  91.              return $self;
  92.          }
  93.  
  94.      Or if you expect people to call not just CLASS->_n_e_w() but also $obj-
  95.      >_n_e_w(), then use something like this.  The _i_n_i_t_i_a_l_i_z_e() method used will
  96.      be of whatever $class we blessed the object into:
  97.  
  98.          sub new {
  99.              my $this = shift;
  100.              my $class = ref($this) || $this;
  101.              my $self = {};
  102.              bless $self, $class
  103.              $self->initialize();
  104.              return $self;
  105.          }
  106.  
  107.      Within the class package, the methods will typically deal with the
  108.      reference as an ordinary reference.  Outside the class package, the
  109.      reference is generally treated as an opaque value that may be accessed
  110.      only through the class's methods.
  111.  
  112.      A constructor may re-bless a referenced object currently belonging to
  113.      another class, but then the new class is responsible for all cleanup
  114.      later.  The previous blessing is forgotten, as an object may belong to
  115.      only one class at a time.  (Although of course it's free to inherit
  116.      methods from many classes.)
  117.  
  118.      A clarification:  Perl objects are blessed.  References are not.  Objects
  119.      know which package they belong to.  References do not.  The _b_l_e_s_s()
  120.      function uses the reference to find the object.  Consider the following
  121.      example:
  122.  
  123.  
  124.  
  125.  
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))                                                          PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  137.  
  138.  
  139.  
  140.          $a = {};
  141.          $b = $a;
  142.          bless $a, BLAH;
  143.          print "\$b is a ", ref($b), "\n";
  144.  
  145.      This reports $b as being a BLAH, so obviously _b_l_e_s_s() operated on the
  146.      object and not on the reference.
  147.  
  148.      AAAA CCCCllllaaaassssssss iiiissss SSSSiiiimmmmppppllllyyyy aaaa PPPPaaaacccckkkkaaaaggggeeee
  149.  
  150.      Unlike say C++, Perl doesn't provide any special syntax for class
  151.      definitions.  You use a package as a class by putting method definitions
  152.      into the class.
  153.  
  154.      There is a special array within each package called @ISA which says where
  155.      else to look for a method if you can't find it in the current package.
  156.      This is how Perl implements inheritance.  Each element of the @ISA array
  157.      is just the name of another package that happens to be a class package.
  158.      The classes are searched (depth first) for missing methods in the order
  159.      that they occur in @ISA.  The classes accessible through @ISA are known
  160.      as base classes of the current class.
  161.  
  162.      If a missing method is found in one of the base classes, it is cached in
  163.      the current class for efficiency.  Changing @ISA or defining new
  164.      subroutines invalidates the cache and causes Perl to do the lookup again.
  165.  
  166.      If a method isn't found, but an AUTOLOAD routine is found, then that is
  167.      called on behalf of the missing method.
  168.  
  169.      If neither a method nor an AUTOLOAD routine is found in @ISA, then one
  170.      last try is made for the method (or an AUTOLOAD routine) in a class
  171.      called UNIVERSAL.  (Several commonly used methods are automatically
  172.      supplied in the UNIVERSAL class; see the section on _D_e_f_a_u_l_t _U_N_I_V_E_R_S_A_L
  173.      _m_e_t_h_o_d_s for more details.)  If that doesn't work, Perl finally gives up
  174.      and complains.
  175.  
  176.      Perl classes do only method inheritance.  Data inheritance is left up to
  177.      the class itself.  By and large, this is not a problem in Perl, because
  178.      most classes model the attributes of their object using an anonymous
  179.      hash, which serves as its own little namespace to be carved up by the
  180.      various classes that might want to do something with the object.
  181.  
  182.      AAAA MMMMeeeetttthhhhoooodddd iiiissss SSSSiiiimmmmppppllllyyyy aaaa SSSSuuuubbbbrrrroooouuuuttttiiiinnnneeee
  183.  
  184.      Unlike say C++, Perl doesn't provide any special syntax for method
  185.      definition.  (It does provide a little syntax for method invocation
  186.      though.  More on that later.)  A method expects its first argument to be
  187.      the object or package it is being invoked on.  There are just two types
  188.      of methods, which we'll call class and instance.  (Sometimes you'll hear
  189.      these called static and virtual, in honor of the two C++ method types
  190.      they most closely resemble.)
  191.  
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))                                                          PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  203.  
  204.  
  205.  
  206.      A class method expects a class name as the first argument.  It provides
  207.      functionality for the class as a whole, not for any individual object
  208.      belonging to the class.  Constructors are typically class methods.  Many
  209.      class methods simply ignore their first argument, because they already
  210.      know what package they're in, and don't care what package they were
  211.      invoked via.  (These aren't necessarily the same, because class methods
  212.      follow the inheritance tree just like ordinary instance methods.)
  213.      Another typical use for class methods is to look up an object by name:
  214.  
  215.          sub find {
  216.              my ($class, $name) = @_;
  217.              $objtable{$name};
  218.          }
  219.  
  220.      An instance method expects an object reference as its first argument.
  221.      Typically it shifts the first argument into a "self" or "this" variable,
  222.      and then uses that as an ordinary reference.
  223.  
  224.          sub display {
  225.              my $self = shift;
  226.              my @keys = @_ ? @_ : sort keys %$self;
  227.              foreach $key (@keys) {
  228.                  print "\t$key => $self->{$key}\n";
  229.              }
  230.          }
  231.  
  232.  
  233.      MMMMeeeetttthhhhoooodddd IIIInnnnvvvvooooccccaaaattttiiiioooonnnn
  234.  
  235.      There are two ways to invoke a method, one of which you're already
  236.      familiar with, and the other of which will look familiar.  Perl 4 already
  237.      had an "indirect object" syntax that you use when you say
  238.  
  239.          print STDERR "help!!!\n";
  240.  
  241.      This same syntax can be used to call either class or instance methods.
  242.      We'll use the two methods defined above, the class method to lookup an
  243.      object reference and the instance method to print out its attributes.
  244.  
  245.          $fred = find Critter "Fred";
  246.          display $fred 'Height', 'Weight';
  247.  
  248.      These could be combined into one statement by using a BLOCK in the
  249.      indirect object slot:
  250.  
  251.          display {find Critter "Fred"} 'Height', 'Weight';
  252.  
  253.      For C++ fans, there's also a syntax using -> notation that does exactly
  254.      the same thing.  The parentheses are required if there are any arguments.
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))                                                          PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  269.  
  270.  
  271.  
  272.          $fred = Critter->find("Fred");
  273.          $fred->display('Height', 'Weight');
  274.  
  275.      or in one statement,
  276.  
  277.          Critter->find("Fred")->display('Height', 'Weight');
  278.  
  279.      There are times when one syntax is more readable, and times when the
  280.      other syntax is more readable.  The indirect object syntax is less
  281.      cluttered, but it has the same ambiguity as ordinary list operators.
  282.      Indirect object method calls are parsed using the same rule as list
  283.      operators: "If it looks like a function, it is a function".  (Presuming
  284.      for the moment that you think two words in a row can look like a function
  285.      name.  C++ programmers seem to think so with some regularity, especially
  286.      when the first word is "new".)  Thus, the parentheses of
  287.  
  288.          new Critter ('Barney', 1.5, 70)
  289.  
  290.      are assumed to surround ALL the arguments of the method call, regardless
  291.      of what comes after.  Saying
  292.  
  293.          new Critter ('Bam' x 2), 1.4, 45
  294.  
  295.      would be equivalent to
  296.  
  297.          Critter->new('Bam' x 2), 1.4, 45
  298.  
  299.      which is unlikely to do what you want.
  300.  
  301.      There are times when you wish to specify which class's method to use.  In
  302.      this case, you can call your method as an ordinary subroutine call, being
  303.      sure to pass the requisite first argument explicitly:
  304.  
  305.          $fred =  MyCritter::find("Critter", "Fred");
  306.          MyCritter::display($fred, 'Height', 'Weight');
  307.  
  308.      Note however, that this does not do any inheritance.  If you wish merely
  309.      to specify that Perl should _S_T_A_R_T looking for a method in a particular
  310.      package, use an ordinary method call, but qualify the method name with
  311.      the package like this:
  312.  
  313.          $fred = Critter->MyCritter::find("Fred");
  314.          $fred->MyCritter::display('Height', 'Weight');
  315.  
  316.      If you're trying to control where the method search begins _a_n_d you're
  317.      executing in the class itself, then you may use the SUPER pseudo class,
  318.      which says to start looking in your base class's @ISA list without having
  319.      to name it explicitly:
  320.  
  321.          $self->SUPER::display('Height', 'Weight');
  322.  
  323.      Please note that the SUPER:: construct is meaningful _o_n_l_y within the
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))                                                          PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  335.  
  336.  
  337.  
  338.      class.
  339.  
  340.      Sometimes you want to call a method when you don't know the method name
  341.      ahead of time.  You can use the arrow form, replacing the method name
  342.      with a simple scalar variable containing the method name:
  343.  
  344.          $method = $fast ? "findfirst" : "findbest";
  345.          $fred->$method(@args);
  346.  
  347.  
  348.      DDDDeeeeffffaaaauuuulllltttt UUUUNNNNIIIIVVVVEEEERRRRSSSSAAAALLLL mmmmeeeetttthhhhooooddddssss
  349.  
  350.      The UNIVERSAL package automatically contains the following methods that
  351.      are inherited by all other classes:
  352.  
  353.      isa(CLASS)
  354.          isa returns _t_r_u_e if its object is blessed into a subclass of CLASS
  355.  
  356.          isa is also exportable and can be called as a sub with two arguments.
  357.          This allows the ability to check what a reference points to. Example
  358.  
  359.              use UNIVERSAL qw(isa);
  360.  
  361.              if(isa($ref, 'ARRAY')) {
  362.                  ...
  363.              }
  364.  
  365.  
  366.      can(METHOD)
  367.          can checks to see if its object has a method called METHOD, if it
  368.          does then a reference to the sub is returned, if it does not then
  369.          _u_n_d_e_f is returned.
  370.  
  371.      VERSION( [NEED] )
  372.          VERSION returns the version number of the class (package).  If the
  373.          NEED argument is given then it will check that the current version
  374.          (as defined by the $VERSION variable in the given package) not less
  375.          than NEED; it will die if this is not the case.  This method is
  376.          normally called as a class method.  This method is called
  377.          automatically by the VERSION form of use.
  378.  
  379.              use A 1.2 qw(some imported subs);
  380.              # implies:
  381.              A->VERSION(1.2);
  382.  
  383.  
  384.      NNNNOOOOTTTTEEEE:::: can directly uses Perl's internal code for method lookup, and isa
  385.      uses a very similar method and cache-ing strategy. This may cause strange
  386.      effects if the Perl code dynamically changes @ISA in any package.
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))                                                          PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  401.  
  402.  
  403.  
  404.      You may add other methods to the UNIVERSAL class via Perl or XS code.
  405.      You do not need to use UNIVERSAL in order to make these methods available
  406.      to your program.  This is necessary only if you wish to have isa
  407.      available as a plain subroutine in the current package.
  408.  
  409.      DDDDeeeessssttttrrrruuuuccccttttoooorrrrssss
  410.  
  411.      When the last reference to an object goes away, the object is
  412.      automatically destroyed.  (This may even be after you exit, if you've
  413.      stored references in global variables.)  If you want to capture control
  414.      just before the object is freed, you may define a DESTROY method in your
  415.      class.  It will automatically be called at the appropriate moment, and
  416.      you can do any extra cleanup you need to do.
  417.  
  418.      Perl doesn't do nested destruction for you.  If your constructor re-
  419.      blessed a reference from one of your base classes, your DESTROY may need
  420.      to call DESTROY for any base classes that need it.  But this applies to
  421.      only re-blessed objects--an object reference that is merely _C_O_N_T_A_I_N_E_D in
  422.      the current object will be freed and destroyed automatically when the
  423.      current object is freed.
  424.  
  425.      WWWWAAAARRRRNNNNIIIINNNNGGGG
  426.  
  427.      An indirect object is limited to a name, a scalar variable, or a block,
  428.      because it would have to do too much lookahead otherwise, just like any
  429.      other postfix dereference in the language.  The left side of -> is not so
  430.      limited, because it's an infix operator, not a postfix operator.
  431.  
  432.      That means that in the following, A and B are equivalent to each other,
  433.      and C and D are equivalent, but A/B and C/D are different:
  434.  
  435.          A: method $obref->{"fieldname"}
  436.          B: (method $obref)->{"fieldname"}
  437.          C: $obref->{"fieldname"}->method()
  438.          D: method {$obref->{"fieldname"}}
  439.  
  440.  
  441.      SSSSuuuummmmmmmmaaaarrrryyyy
  442.  
  443.      That's about all there is to it.  Now you need just to go off and buy a
  444.      book about object-oriented design methodology, and bang your forehead
  445.      with it for the next six months or so.
  446.  
  447.      TTTTwwwwoooo----PPPPhhhhaaaasssseeeedddd GGGGaaaarrrrbbbbaaaaggggeeee CCCCoooolllllllleeeeccccttttiiiioooonnnn
  448.  
  449.      For most purposes, Perl uses a fast and simple reference-based garbage
  450.      collection system.  For this reason, there's an extra dereference going
  451.      on at some level, so if you haven't built your Perl executable using your
  452.      C compiler's -O flag, performance will suffer.  If you _h_a_v_e built Perl
  453.      with cc -O, then this probably won't matter.
  454.  
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))                                                          PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  467.  
  468.  
  469.  
  470.      A more serious concern is that unreachable memory with a non-zero
  471.      reference count will not normally get freed.  Therefore, this is a bad
  472.      idea:
  473.  
  474.          {
  475.              my $a;
  476.              $a = \$a;
  477.          }
  478.  
  479.      Even thought $a _s_h_o_u_l_d go away, it can't.  When building recursive data
  480.      structures, you'll have to break the self-reference yourself explicitly
  481.      if you don't care to leak.  For example, here's a self-referential node
  482.      such as one might use in a sophisticated tree structure:
  483.  
  484.          sub new_node {
  485.              my $self = shift;
  486.              my $class = ref($self) || $self;
  487.              my $node = {};
  488.              $node->{LEFT} = $node->{RIGHT} = $node;
  489.              $node->{DATA} = [ @_ ];
  490.              return bless $node => $class;
  491.          }
  492.  
  493.      If you create nodes like that, they (currently) won't go away unless you
  494.      break their self reference yourself.  (In other words, this is not to be
  495.      construed as a feature, and you shouldn't depend on it.)
  496.  
  497.      Almost.
  498.  
  499.      When an interpreter thread finally shuts down (usually when your program
  500.      exits), then a rather costly but complete mark-and-sweep style of garbage
  501.      collection is performed, and everything allocated by that thread gets
  502.      destroyed.  This is essential to support Perl as an embedded or a
  503.      multithreadable language.  For example, this program demonstrates Perl's
  504.      two-phased garbage collection:
  505.  
  506.          #!/usr/bin/perl
  507.          package Subtle;
  508.  
  509.          sub new {
  510.              my $test;
  511.              $test = \$test;
  512.              warn "CREATING " . \$test;
  513.              return bless \$test;
  514.          }
  515.  
  516.          sub DESTROY {
  517.              my $self = shift;
  518.              warn "DESTROYING $self";
  519.          }
  520.  
  521.          package main;
  522.  
  523.  
  524.  
  525.                                                                         PPPPaaaaggggeeee 8888
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))                                                          PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  533.  
  534.  
  535.  
  536.          warn "starting program";
  537.          {
  538.              my $a = Subtle->new;
  539.              my $b = Subtle->new;
  540.              $$a = 0;  # break selfref
  541.              warn "leaving block";
  542.          }
  543.  
  544.          warn "just exited block";
  545.          warn "time to die...";
  546.          exit;
  547.  
  548.      When run as /_t_m_p/_t_e_s_t, the following output is produced:
  549.  
  550.          starting program at /tmp/test line 18.
  551.          CREATING SCALAR(0x8e5b8) at /tmp/test line 7.
  552.          CREATING SCALAR(0x8e57c) at /tmp/test line 7.
  553.          leaving block at /tmp/test line 23.
  554.          DESTROYING Subtle=SCALAR(0x8e5b8) at /tmp/test line 13.
  555.          just exited block at /tmp/test line 26.
  556.          time to die... at /tmp/test line 27.
  557.          DESTROYING Subtle=SCALAR(0x8e57c) during global destruction.
  558.  
  559.      Notice that "global destruction" bit there?  That's the thread garbage
  560.      collector reaching the unreachable.
  561.  
  562.      Objects are always destructed, even when regular refs aren't and in fact
  563.      are destructed in a separate pass before ordinary refs just to try to
  564.      prevent object destructors from using refs that have been themselves
  565.      destructed.  Plain refs are only garbage-collected if the destruct level
  566.      is greater than 0.  You can test the higher levels of global destruction
  567.      by setting the PERL_DESTRUCT_LEVEL environment variable, presuming
  568.      -DDEBUGGING was enabled during perl build time.
  569.  
  570.      A more complete garbage collection strategy will be implemented at a
  571.      future date.
  572.  
  573. SSSSEEEEEEEE AAAALLLLSSSSOOOO
  574.      A kinder, gentler tutorial on object-oriented programming in Perl can be
  575.      found in the _p_e_r_l_t_o_o_t manpage.  You should also check out the _p_e_r_l_b_o_t
  576.      manpage for other object tricks, traps, and tips, as well as the
  577.      _p_e_r_l_m_o_d_l_i_b manpage for some style guides on constructing both modules and
  578.      classes.
  579.  
  580.  
  581.  
  582.  
  583.  
  584.  
  585.  
  586.  
  587.  
  588.  
  589.  
  590.  
  591.                                                                         PPPPaaaaggggeeee 9999
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))                                                          PPPPEEEERRRRLLLLOOOOBBBBJJJJ((((1111))))
  599.  
  600.  
  601.  
  602.  
  603.  
  604.  
  605.  
  606.  
  607.  
  608.  
  609.  
  610.  
  611.  
  612.  
  613.  
  614.  
  615.  
  616.  
  617.  
  618.  
  619.  
  620.  
  621.  
  622.  
  623.  
  624.  
  625.  
  626.  
  627.  
  628.  
  629.  
  630.  
  631.  
  632.  
  633.  
  634.  
  635.  
  636.  
  637.  
  638.  
  639.  
  640.  
  641.  
  642.  
  643.  
  644.  
  645.  
  646.  
  647.  
  648.  
  649.  
  650.  
  651.  
  652.  
  653.  
  654.                                                                        PPPPaaaaggggeeee 11110000
  655.  
  656.  
  657.  
  658.  
  659.  
  660.  
  661.